12. Exercise: Create the drawClippedRectangle() Method
23 12 AAK DrawClippedRectangle
Android Developer Documentation
Exercise
In this exercise you will create the drawClippedRectangle() method.
- Create a
drawClippedRectangle()method that takes an argumentcanvasof typeCanvas.
private fun drawClippedRectangle(canvas: Canvas) {
}
- Inside the
drawClippedRectangle()method, set the boundaries of the clipping rectangle for the whole shape. Apply a clipping rectangle that constrains to drawing only the square.
canvas.clipRect(
clipRectLeft,clipRectTop,
clipRectRight,clipRectBottom
)
The Canvas.clipRect(left, top, right, bottom) method reduces the region of the screen that future draw operations can write to. It sets the clipping boundaries to be the spatial intersection of the current clipping rectangle and the rectangle passed into clipRect(). There are a lot of variants of the clipRect() method that accept different forms of regions and allow different operations on the clipping rectangle. Check the linked documentation to learn more.
- Add code to fill the
canvaswith white color. Only the region inside the clipping rectangle will be filled!
canvas.drawColor(Color.WHITE)
- Change the color to red and draw a diagonal line inside the clipping rectangle.
paint.color = Color.RED
canvas.drawLine(
clipRectLeft,clipRectTop,
clipRectRight,clipRectBottom,paint
)
- Set the color to green and draw a circle inside the clipping rectangle.
paint.color = Color.GREEN
canvas.drawCircle(
circleRadius,clipRectBottom - circleRadius,
circleRadius,paint
)
- Set the color to blue and draw text aligned with the right edge of the clipping rectangle. Use Canvas.drawText() to draw text.
paint.color = Color.BLUE
// Align the RIGHT side of the text with the origin.
paint.textSize = textSize
paint.textAlign = Paint.Align.RIGHT
canvas.drawText(
context.getString(R.string.clipping),
clipRectRight,textOffset,paint
)
Note: The Paint.Align property specifies which side of the text to align to the origin (not which side of the origin the text goes, or where in the region it is aligned!). Aligning the right side of the text to the origin places it on the left of the origin.